package com.yhuk.oauth.server.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author xiaolang
 * @version 1.0.0
 */
@Configuration
@Order(1)
@MapperScan(basePackages = "com.yhuk.oauth.server.dao.oauth", sqlSessionTemplateRef = "oauthSqlSessionTemplate")
public class OAuthDataSourceConfig {

    @Bean(name = "oauthDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.oauth")
    public DataSource oauthDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置session工厂
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "oauthSqlSessionFactory")
    public SqlSessionFactory oauthSqlSessionFactory(@Qualifier("oauthDataSource") DataSource dataSource) throws  Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:"));
        return bean.getObject();
    }

    /**
     * 配置事务
     * @param dataSource
     * @return
     */
    @Bean(name = "oauthTransactionManager")
    @Primary
    public DataSourceTransactionManager oauthTransactionManager(@Qualifier("oauthDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 模版
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "oauthSqlSessionTemplate")
    public SqlSessionTemplate oauthSqlSessionTemplate(@Qualifier("oauthSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
